<template>
  <div>
    <el-dialog
      :visible.sync="dialogVisible"
      :close-on-click-modal="false"
      :append-to-body="true"
      title="选择商品"
      width="850px"
      @close="close"
    >
      <div v-loading="loading">
        <!-- filter start -->
        <div class="filter-container">
          <el-form ref="filterForm" :model="filterForm" label-width="100px" size="small">
            <el-row>
              <el-col :span="12">
                <el-form-item prop="title" label="商品名称：">
                  <el-input v-model="filterForm.title" />
                </el-form-item>
                <el-form-item prop="goodsNo" label="商品编码：">
                  <el-input v-model="filterForm.goodsNo" />
                </el-form-item>
              </el-col>
              <el-col :span="12">
                <el-form-item prop="goodsType" label="商品类型：">
                  <el-select v-model="filterForm.goodsType" placeholder="请选择">
                    <el-option label="全部" value="all" />
                    <el-option v-for="(item,key) in goodsTypeOptions" :key="key" :label="item" :value="key" />
                  </el-select>
                </el-form-item>
                <!-- <el-form-item prop="goodsType" label="配送方式：">
                  <el-select v-model="filterForm.goodsDelivery" placeholder="请选择">
                    <el-option label="全部" value="all"></el-option>
                    <el-option
                      v-for="(item,key) in goodsDeliveryOptions"
                      :key="key"
                      :label="item"
                      :value="key"
                    ></el-option>
                  </el-select>
                </el-form-item>-->
                <el-form-item prop="categoryId" label="商品类目：">
                  <el-cascader
                    v-model="filterForm.categoryId"
                    :options="categoryTreeOptions"
                    :show-all-levels="false"
                    :props="{ expandTrigger: 'hover',checkStrictly: true,label:'title' ,value:'id'}"
                    class="w-300"
                  />
                </el-form-item>
              </el-col>
            </el-row>

            <!-- <el-form-item prop="title" label="商品状态：">
          <el-select v-model="filterForm.status" placeholder="请选择">
            <el-option label="全部" value="all"></el-option>
            <el-option v-for="(item,key) in statusOptions" :key="key" :label="item" :value="key"></el-option>
          </el-select>
            </el-form-item>-->
            <el-form-item>
              <el-button type="primary" round @click="search">查 询</el-button>
              <el-button round @click="reset">重 置</el-button>
            </el-form-item>
          </el-form>
        </div>
        <!-- filter end -->

        <!-- table start -->
        <!-- 新增服务 -->

        <div class="table-container">
          <el-table
            :data="list"
            border
            stripe
            style="width: 100%"
            size="small"
            element-loading-text="加载中"
            empty-text="暂无数据"
          >
            <el-table-column prop="title" label="商品标题" />
            <el-table-column prop="defaulted" label="商品类型" width="100">
              <template slot-scope="scope">{{ goodsTypeOptions[scope.row.goodsType] }}</template>
            </el-table-column>
            <el-table-column prop="categoryName" label="商品类目">
              <template slot-scope="scope">
                <span v-if="scope.row.categoryName">
                  <span v-for="(item,index) in scope.row.categoryName" :key="index">
                    {{ item }}
                    <span v-if="index+1!==scope.row.categoryName.length">/</span>
                  </span>
                </span>
                <span v-else>无</span>
              </template>
            </el-table-column>
            <el-table-column label="选择" width="100">
              <template slot-scope="scope">
                <!-- <el-radio
                  v-model="form.goodsId"
                  :label="scope.row.goodsId"
                  @change="chooseGoods(scope.row)"
                >选择</el-radio>-->
                <!--  <el-button :disabled="hasCheckedIds.includes(scope.row.goodsId)" type="text" @click="chooseGoods(scope.row)">
                  {{ hasCheckedIds.includes(scope.row.goodsId) ? '已选择' : '选择' }}
                </el-button>-->
                <el-checkbox
                  v-model="checkedIds"
                  :disabled="originalCheckedIds.includes(scope.row.goodsId)"
                  :label="scope.row.goodsId"
                  @change="(val)=>checkboxChange(val,scope.row)"
                >
                  {{ checkedIds.includes(scope.row.goodsId) ? '已选' : '选择' }}
                </el-checkbox>
              </template>
            </el-table-column>
          </el-table>
          <!-- 分页 -->
          <pagination-direction
            v-if="paginationConfig.total!==0"
            :config="paginationConfig"
            @sizeschange="sizesChange"
            @pagechange="pageChange"
          />
        </div>
        <!-- table end -->
      </div>
      <div slot="footer" class="dialog-footer">
        <el-button :disabled="loading||checkedList.length===0" size="small" round type="primary" @click="submit">
          确定<span>（ 已选 {{ checkedList.length }}  ）</span></el-button>
        <el-button :disabled="loading" size="small" round @click="cancel">取消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { productList } from '@/views/wxaMallModule/api/product'
import { categoryTree } from '@/views/wxaMallModule/api/category'

export default {
  data() {
    return {
      // 配置
      resolve: null,
      reject: null,
      goodsTypeOptions: {
        100: '实物商品',
        // 101: '配件商品',
        200: '卡/券包'
        // 300: "同城配送",
      },
      goodsDeliveryOptions: {
        // 1: "canExpress",
        2: '同城配送',
        3: '到店自提'
        // 3: "券包",
        // 300: "同城配送",
      },
      statusOptions: {
        0: '已下架',
        1: '已上架'
      },
      categoryTreeOptions: [],
      // 分页配置
      paginationConfig: {
        direction: 'center', // 分页位置
        layout: 'total, sizes, prev, pager, next, jumper', // 分页类型
        pageSizes: [10, 20], // 分页pages
        total: 0,
        page: 1, // 页数-默认1
        pageSize: 10 // 每页条数-默认10
      },
      // 状态
      dialogVisible: null,
      loading: false,
      // 数据
      value: '',
      filterForm: {
        goodsType: 'all',
        barCode: '',
        brandId: '',
        categoryId: [0],
        goodsSerial: '',
        goodsNo: '',
        status: 1,
        title: ''
        // goodsDelivery: "2",
      },
      form: {
        goodsId: null
      },
      originalCheckedIds: [],
      checkedIds: [],
      checkedList: [],
      list: []
    }
  },
  computed: {},
  watch: {},
  created() {
  },
  mounted() {
  },

  methods: {
    /**
     * 弹框相关
     */
    open({ hasCheckedIds = [] }) {
      console.log(hasCheckedIds)
      this.originalCheckedIds = hasCheckedIds
      this.checkedIds = hasCheckedIds
      this.fetchData()
      this.getCategoryOptions()
      this.show()
      return new Promise((resolve, reject) => {
        this.resolve = resolve
        this.reject = reject
      })
    },

    show() {
      this.dialogVisible = true
    },

    close() {
      this.loading = false
      Object.assign(this.$data, this.$options.data())
      this.originalCheckedIds = []
      this.checkedIds = []
      this.checkedList = []
      this.list = []
      this.form = {
        goodsId: null
      }
    },

    hide() {
      this.resolve = null
      this.reject = null
      this.dialogVisible = false
    },

    /**
     * 数据组
     */
    fetchData(
      pageNum = this.paginationConfig.page,
      pageSize = this.paginationConfig.pageSize
    ) {
      // 加入page
      this.filterForm.pageNum = pageNum
      this.filterForm.pageSize = pageSize
      const params = Object.assign({}, this.filterForm)
      if (
        params.categoryId.length === 0 ||
          (params.categoryId.length === 1 && params.categoryId[0] === 0)
      ) {
        params.categoryId = ''
      } else {
        params.categoryId = params.categoryId[params.categoryId.length - 1]
      }
      if (params.goodsType === 'all') params.goodsTypes = [100, 200]
      // 清除多余字段
      for (const key in params) {
        if (params[key] === '' || params[key] === 'all') {
          delete params[key]
        }
      }
      this.loading = true
      productList(params)
        .then((res) => {
          this.list = res.data.list
          this.paginationConfig.total = res.data.total
          this.paginationConfig.page = res.data.pageNum
        })
        .finally(() => {
          this.filterForm.goodsSerial = null
          this.loading = false
        })
    },

    // 分页sizes改变
    sizesChange() {
      this.fetchData()
    },

    // 分页page改变
    pageChange() {
      this.fetchData()
    },

    // 获取类目tree
    getCategoryOptions() {
      return new Promise((resolve, reject) => {
        categoryTree()
          .then((res) => {
            this.categoryTreeOptions = [
              {
                categoryNo: '',
                children: undefined,
                id: 0,
                parentId: 0,
                ranking: 0,
                title: '全部'
              }
            ].concat(this.formatTreeData(res.data))
          })
          .catch((err) => {
          })
          .finally(() => {
          })
      })
    },

    // 递归children设置空
    formatTreeData(data) {
      for (var i = 0; i < data.length; i++) {
        if (data[i].children.length < 1) {
          data[i].children = undefined
        } else {
          this.formatTreeData(data[i].children)
        }
      }
      return data
    },

    /**
     * 按钮组
     */
    // 查询
    search() {
      this.fetchData(1)
    },

    // 重置
    reset() {
      this.$refs.filterForm.resetFields()
    },

    // 保存
    submit() {
      if (this.checkedList.length) this.resolve && this.resolve(this.checkedList)
      this.hide()
    },

    // 取消
    cancel() {
      this.hide()
    },

    // 选择
    // chooseGoods(row) {
    //   const params = {
    //     goodsId: row.goodsId,
    //     coverImg: row.coverImg,
    //     title: row.title,
    //     subTitles: row.subTitle,
    //     category: row.categoryName
    //   }
    //   this.resolve && this.resolve(params)
    //   this.hide()
    // },

    /*
    * 状态组
    * */
    // 多选
    checkboxChange(val, row) {
      if (val) {
        const params = {
          goodsId: row.goodsId,
          coverImg: row.coverImg,
          title: row.title,
          subTitles: row.subTitle,
          category: row.categoryName
        }
        this.checkedList.push(params)
      } else {
        this.checkedList.splice(this.checkedList.findIndex(item => item.couponId === row.id), 1)
      }
    }
    /**
     * 方法组
     */
  }
}
</script>
<style rel="stylesheet/scss" lang="scss" scoped>
</style>
